package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.api.users.UserServiceFactory;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * User: lunin
 * Date: 4/22/14
 * Time: 6:56 PM
 */
class TabNameServant implements Servant {

    private static final Logger LOG = Logger.getLogger(TabNameServant.class.getName());
    private static final String LOGOFF_URL = "logout";
    private static final String REDIRECT_URI = "/admin/admin.html";

    private static class TabEntry {
        private static final String NAME = "name";
        private static final String CONTENT = "content";
        private static final String IS_MAIN = "isMain";

        String tabname;
        String templateUrl;
        boolean isMain;

        public TabEntry(String name, String content, boolean main) {
            this.tabname = name;
            this.templateUrl = content;
            this.isMain = main;
        }

        public JSONObject toJson() {
            JSONObject thisObject = new JSONObject();
            thisObject.put(NAME, tabname);
            thisObject.put(CONTENT, templateUrl);
            thisObject.put(IS_MAIN, isMain);
            return thisObject;
        }
    }

    private static final List<TabEntry> BASIC_ENTRIES;
    static {
        List<TabEntry> temp = new LinkedList<TabEntry>();
        temp.add(new TabEntry("Achievement Generator", "", true));
        temp.add(new TabEntry("View Achievements", "parts/achievementTable.html", false));
        temp.add(new TabEntry("View Students", "parts/studentTable.html", false));
        BASIC_ENTRIES = Collections.unmodifiableList(temp);
    }

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        JSONArray array = new JSONArray();
        JSONArray tubSubArray = new JSONArray();
        for (TabEntry e : BASIC_ENTRIES) {
            tubSubArray.put(e.toJson());
        }
        if (req.isUserInRole("admin")) {
            tubSubArray.put(new TabEntry("View Curators", "parts/curatorTable.html", false).toJson());
        }
        try {
            array.put(tubSubArray);
            JSONObject logoutUrl = new JSONObject();
            logoutUrl.put(LOGOFF_URL, UserServiceFactory.getUserService().createLogoutURL(REDIRECT_URI));
            array.put(logoutUrl);
            array.write(resp.getWriter());
        } catch (IOException e) {
            LOG.severe("Error while writing tab output " + e);
        }
    }
}
